<template>
  <div class="app-container">




    <el-form :model="form" label-width="80px" >

      <el-form-item label="分类">
        <el-cascader placeholder="分类"
         v-model="selectClassifyId"
         :options="classifies"
         :props="{ expandTrigger: 'hover' ,value:'id',label:'name'}"
         @change="getSpec" >
        </el-cascader>
      </el-form-item>

      <el-form-item label="品牌">
        <el-select v-model="form.brand_id" placeholder="请选择品牌">
          <el-option v-for="(item,index) in brands" :label="item.name" :value="item.id" :key="index"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="商品名称" >
        <el-input v-model="form.name"></el-input>
      </el-form-item>

      <el-form-item label="商品描述">
        <el-input type="textarea" v-model="form.desc_detail" rows="4"></el-input>
      </el-form-item>

      <el-form-item label="封面">
        <el-upload
          :action="host+'/guard/upload?module=goods'"
          list-type="picture-card"
          :on-success="handleAvatarSuccess"
          :on-remove="handleRemove">
          <i class="el-icon-plus"></i>
        </el-upload>
<!--        <el-dialog :visible.sync="dialogVisible">
          <img width="100%" :src="dialogImageUrl" alt="">
        </el-dialog>-->
      </el-form-item>

      <el-form-item v-if="specs.length>0" label="规格">
        <el-card class="box-card">
          <div v-for="(item,index) in specs" :key="index" style="margin-bottom: 25px">
            <span style="margin-right: 10px">{{item.name}}：</span>
            <el-checkbox-group  v-model="selectSpecValues[index]" @change="getSelectSpecValues">
              <el-checkbox  v-for="(attr,index1) in item.get_spec_value" :label="attr.name"  :key="index1"></el-checkbox>
              <div style="float: right">
                <el-input style="width: 200px;height: 5px;margin-left: 30px"  v-model="item.new" placeholder="属性" ></el-input>
                <el-button style="margin-left: 10px"  type="primary" @click="addSpecValue(index)">添加</el-button>
              </div>
            </el-checkbox-group>

          </div>
        </el-card>
      </el-form-item>

      <el-row v-for="(item,index) in resultSpecValues" :key="index">
          <el-col  :span="4">
            <el-form-item label="规格">
              <el-input v-model="item.tag" placeholder=""></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="sku名称">
              <el-input v-model="item.name" placeholder="sku名称"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="副标题">
              <el-input v-model="item.sub_title" placeholder="副标题"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="库存">
              <el-input v-model="item.stock" placeholder="库存"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="单价">
              <el-input v-model="item.price" placeholder="单价"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="进价">
              <el-input v-model="item.cost_price" placeholder="进价"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="市场价">
              <el-input v-model="item.market_price" placeholder="市场价"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="图片">
              <el-upload
                class="avatar-uploader"
                :action="host+'/guard/upload?module=goods'"
                :show-file-list="false"
                :on-success="(response,file,fileList)=>handleSkuImgSuccess(response,file,fileList,index)"
                :before-upload="beforeAvatarUpload">
                <img v-if="item.img_url" :src="host+item.img_url" class="avatar" alt="封面">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="状态">
              <el-switch
                :active-value="1"
                :inactive-value="2"
                active-text="上架"
                inactive-text="下架"
                v-model.number="item.status"
                >
              </el-switch>
            </el-form-item>
          </el-col>
      </el-row>


      <el-form-item>
        <el-button type="primary" @click="onSubmit" >立即创建</el-button>
        <el-button>取消</el-button>
      </el-form-item>


    </el-form>
  </div>
</template>

<script>

import {myGet, myPost} from "@/utils/myUtils";

const urlBrandLst = '/guard/shop/goods/brand/lst'
const urlGetSpecLst = '/guard/shop/goods/spec/lst'
const urlAddSpecValue = '/guard/shop/goods/spec/value/add'
const urlSpuAdd = '/guard/shop/goods/spu/add'

export default {

  data() {
    return {
      host:process.env.VUE_APP_HOST,
      brands:[],
      classifies:[],
      selectClassifyId:[],
      specs:[],
      selectSpecValues:[],
      dialogImageUrl: '',
      form:{
        name:"",
        brand_id:"",
        desc_detail:"",
        cover_urls:[],
      },
      resultSpecValues:[],//最终要提交的

    };
  },

  mounted() {
    this.getBrandAndClassifyLst()

  },

  methods: {

    onSubmit(){
      myPost(urlSpuAdd,{
        spuInfo:this.form,
        skuInfo:this.resultSpecValues,
        selectClassifyId:this.selectClassifyId
      }).then(res=>{
        if(res.status){
          this.$message.success(res.msg)
          this.$router.push('/spu/index')
        }
      })
    },
    getBrandAndClassifyLst(){
      myGet(urlBrandLst).then(res=>{
        if(res.status){
          this.brands = res.data.records
          this.classifies = res.data.classifies
        }
      })
    },
    getSpec(){
      const id = this.selectClassifyId[this.selectClassifyId.length-1]

      myGet(urlGetSpecLst,{selectClassifyId:id}).then(res=>{
        if(res.status){
          if(res.data.records.length>0){
            this.specs = res.data.records
            this.specs.forEach(()=>{
              this.selectSpecValues.push([])
            })
          }
        }
      })
    },
    getSelectSpecValues(value){
      let info = []
      this.selectSpecValues.forEach(item=>{
        if(item.length>0){
          info.push(item)
        }
      })
      info = this.calcDescartes(info)
      this.resultSpecValues = []
      info.forEach(item=>{
        if(item instanceof Array){
          this.resultSpecValues.push({
            tag:item.join(' - '),
            name:'',
            sub_title:'',
            stock:0,
            price:0,//单价：正常的销售价格
            cost_price:0,//进价：成本价
            market_price:0,//市场价：真正出售的价格（做活动，打折之类的）
            img_url:"",
            status:1
          })
        }
      })


    },
    //笛卡尔积
    calcDescartes(array) {
      if (array.length < 2) return array[0] || [];
      return [].reduce.call(array, function (col, set) {
        var res = [];
        col.forEach(function (c) {
          set.forEach(function (s) {
            var t = [].concat(Array.isArray(c) ? c : [c]);
            t.push(s);
            res.push(t);
          })
        });
        return res;
      });
    },

    addSpecValue(index){
      const name = this.specs[index].new
      const spec_id = this.specs[index].id
      myGet(urlAddSpecValue,{name,spec_id}).then(res=>{
        if(res.status){
          this.specs[index].get_spec_value.push({
            value:res.data.records.id,
            name:res.data.records.name
          })
        }
      })
    },

    handleRemove(file, imgList) {
      const uid = file.uid
      const index = this.form.cover_urls.findIndex((item)=>{
        return item.uid == uid
      })
     this.form.cover_urls.splice(index,1)
    },
    /*handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },*/
    handleAvatarSuccess(res, file) {
      this.form.cover_urls.push({
        uid:file.uid,
        url:res.data.records.filePath
      });
    },
    handleSkuImgSuccess(res, file,fileList,index) {
      this.resultSpecValues[index].img_url = res.data.records.filePath
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg,png';
      const isLt2M = file.size / 1024 / 1024 < 2;

      /*if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!');
      }*/
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    }

  },
};
</script>

<style >
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 60px;
    height: 60px;
    line-height: 60px;
    text-align: center;
  }
  .avatar {
    width: 60px;
    height: 60px;
    display: block;
  }
</style>
